package com.ziki.bswicket.template.crud.page;

import org.apache.wicket.model.CompoundPropertyModel;

import com.ziki.bswicket.action.ClickAction;
import com.ziki.bswicket.action.SubmitAction;
import com.ziki.bswicket.component.BsForm;
import com.ziki.bswicket.component.BsHidden;
import com.ziki.bswicket.component.BsSubmitLink;
import com.ziki.bswicket.component.BsTextField;
import com.ziki.bswicket.page.BsPage;
import com.ziki.bswicket.template.base.BaseTemplatePage;
import com.ziki.bswicket.template.crud.model.CrudModel;
import com.ziki.bswicket.template.crud.service.CrudService;

public class CrudEditPage extends BaseTemplatePage {
    private static final long serialVersionUID = 1L;
    private CrudService crudService = new CrudService();

    public CrudEditPage(final String id) {
        init(getArticle(id));
    }

    public CrudEditPage(final CrudModel article) {
        init(article);
    }

    private void init(final CrudModel article) {
        CompoundPropertyModel<CrudModel> model = new CompoundPropertyModel<>(article);
        BsForm<CrudModel> form = new BsForm<>("form", model);
        add(form);
        form.add(new BsHidden<String>("id"));
        form.add(new BsTextField<String>("title"));
        BsSubmitLink submit = new BsSubmitLink("submit");
        submit.add(submitAction(this, form.getModelObject(), form));
        // submit.setDefaultFormProcessing(false);
        form.add(submit);
        // form.add(submitAction());
    }

    public CrudModel getArticle(final String id) {
        CrudModel result = crudService.getArticle(id);
        System.out.println(result);
        return result;
    }

    private SubmitAction submitAction(final BsPage page, final CrudModel article, final BsForm<CrudModel> form) {
        return new SubmitAction() {
            @Override
            public void performSubmit() {
                CrudModel a = form.getModelObject();
                System.out.println("form " + a.getTitle());
                System.out.println("CrudModel " + article.getTitle());
                System.out.println(a);
                System.out.println(article);
                // dao.edit(article);
                page.setResponsePage(CrudListPage.class);
            }
        };
    }

    public static ClickAction editActions(final String id, final BsPage page) {
        return new ClickAction() {
            @Override
            public void performClick() {
                page.setResponsePage(new CrudEditPage(id));
            }
        };
    }
}
